<template>
  <div>
    <div class="chat-box">
      <chat-header />
      <div class="chat-box-content">
        <div class="search-box">
          <el-input @input="inputHandle" v-model="searchValue" placeholder="搜索您的好友或想添加的人吧" />
        </div>
        <div ref="friendListScroll" class="friend-wrap">
          <div class="friend-list">
            <chat-card @chooseChat="chooseChat" v-for="friend in list" :key="friend.id" :friend="friend" />
          </div>
        </div>
      </div>
    </div>
    <chat-dialog :user="user" v-if="showMessage" />
  </div>
</template>

<script>
import BScroll from '@better-scroll/core';
import { Input } from 'element-ui';
import axios from '../../helper/axios';
import debounce from '../../helper/debounce';
import Dialog from './dialog.vue';
import Card from './card.vue';
import Header from './header.vue';

export default {
  filters: {
    test(value, a, b) {
      return value + 1 + a + b;
    },
  },
  components: {
    'el-input': Input,
    'chat-header': Header,
    'chat-dialog': Dialog,
    'chat-card': Card,
  },
  data() {
    return {
      showMessage: false,
      searchValue: '',
      list: [],
      text: 'hahaha',
      user: {},
    };
  },
  mounted() {
    this.friendListScroll = new BScroll(this.$refs.friendListScroll);

    axios.get('/api/friend/list', {
      params: { status: 2 },
    }).then((res) => {
      this.list = res.friendlist;
      this.$nextTick().then(() => {
        this.friendListScroll.refresh();
      });
    });
  },
  methods: {
    chooseChat(user) {
      this.showMessage = true;
      this.user = user;
    },
    // eslint-disable-next-line
    inputHandle: debounce(function(value) {
      if (!value) {
        axios.get('/api/friend/list', {
          params: { status: 2 },
        }).then((res) => {
          this.list = res.friendlist;
          this.$nextTick().then(() => {
            this.friendListScroll.refresh();
          });
        });
        return;
      }

      axios.get('/api/user/list', {
        params: {
          nickname: value,
        },
      }).then((res) => {
        this.list = res.userlist;
        this.$nextTick().then(() => {
          this.friendListScroll.refresh();
        });
      });
    }, 1000),
  },
};
</script>

<style>
.chat-box {
  width: 280px;
  height: 100vh;
  border: 1px solid #979797;
  border-radius: 0 15px 15px 0;
  box-sizing: border-box;
  overflow: hidden;
}

.search-box {
  width: 260px;
  height: 40px;
  margin: 10px;
  background-color: #f5f5f5;
}

.friend-wrap {
  height: calc(100vh - 180px);
  overflow: hidden;
}
</style>
